package cn.cefoc.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;


@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 获取请求上下文
        RequestContext currentContext = RequestContext.getCurrentContext();
        // 获取请求路径
        HttpServletRequest request = currentContext.getRequest();
        String requestURI = request.getRequestURI();
        // 如果访问的是公共路径，返回false,不执行run方法
        if (requestURI.endsWith("login")||requestURI.endsWith("register")){
            return false;
        }
        // 访问的不是公共路径，返回true,执行run方法
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 判断是否有token
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        response.setContentType("application/json;charset=utf-8");

        String token = request.getHeader("token");
        // 如果token为空,响应给用户，并阻断过滤器
        if (StringUtils.isEmpty(token)){
            // 设置响应内容
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
                HashMap<String, Object> map = new HashMap<>();
                map.put("success",false);
                map.put("message","信息为空");
                map.put("resultObj","noLogin");
                // 导入fastJson的依赖包，将map转换为json字符串
                String s = JSONObject.toJSONString(map);
                writer.write(s);
                // 2.阻止后续filter执行
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        // 要放行的话，返回值不用管
        return null;
    }
}
